package com.example.service;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.entity.Users;
import com.example.mapper.*;
import com.example.utils.*;
import com.example.entity.SMSParameter;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * The type User service.
 */
@Service
public class UserService {

    @Autowired
    private UsersMapper mapper;
    @Resource
    private RedisUtils redisUtils;

    /**
     * Get user all result data.
     *
     * @return the result data
     */
    public ResultData GetUserAll() {

        List<Users> res = mapper.selectList(null);
        if (res.isEmpty()) {
            throw new BisException("暂无友链");
        } else {
            return ResultUtils.sucuss("查询成功", res);
        }

    }

    /**
     * Sets notice.
     *
     * @param notice the notice
     * @return the notice
     */
    public ResultData setNotice(Object notice) {

        boolean res = redisUtils.set("Notice", notice);
        if (res) {
            return ResultUtils.sucuss("公告更新成功", true);
        } else {
            throw new BisException("公告更新失败");
        }
    }

    /**
     * Gets notice.
     *
     * @return the notice
     */
    public ResultData getNotice() {

        Object result = redisUtils.get("Notice");
        if (!result.equals("")) {
            return ResultUtils.sucuss("公告查询成功", result);
        } else {
            throw new BisException("公告查询失败");
        }
    }

    /**
     * Sets user ju.
     *
     * @param users the users
     * @return the user ju
     */
    public ResultData setUserJu(Users users) {
        if (users.getUserJurisdiction().equals("1")) {
            users.setUserJurisdiction("0");
        } else {
            users.setUserJurisdiction("1");
        }
        UpdateWrapper<Users> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id", users.getUserId());
        updateWrapper.set("user_jurisdiction", users.getUserJurisdiction());
        int res = mapper.update(null, updateWrapper);
        if (res > 0) {
            return ResultUtils.sucuss("管理员操作成功", res);
        } else {
            return ResultUtils.sucuss("设置管理员失败", res);
        }

    }

    /**
     * Del user by id result data.
     *
     * @param users the users
     * @return the result data
     */
    public ResultData delUserByID(Users users) {

        if (!String.valueOf(users.getUserJurisdiction()).equals("1")) {
            int res = mapper.deleteById(users.getUserId());
            if (res == 0) {
                throw new BisException("删除失败");
            } else {
                return ResultUtils.sucuss("删除成功", res);
            }
        } else {
            throw new BisException("你没有权限删除此用户。");
        }

    }

    /**
     * User login result data.
     *
     * @param user the user
     * @return the result data
     */
    public ResultData UserLogin(Users user) {

        if (user.getUserPhone().equals("") || user.getUserPassword().equals("")) {
            return ResultUtils.error("账号或密码为空", null);
        } else {
            String md5Paw = DigestUtils.md5DigestAsHex(user.getUserPassword().getBytes());
            QueryWrapper<Users> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("user_phone", user.getUserPhone()).eq("user_password", md5Paw);
            List<Users> res = mapper.selectList(userQueryWrapper);

            if (ObjectUtils.isEmpty(res)) {
                return ResultUtils.error("账号或密码错误", res);
            } else {
                Map<String, String> map = new HashMap<>();
                map.put("userPhone", user.getUserPhone());
                String token = JwtUtils.getToken(map);
                user.setUserToken(token);
                UpdateWrapper<Users> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("user_phone", user.getUserPhone()).set("user_token", user.getUserToken());
                mapper.update(null, updateWrapper);
                return ResultUtils.sucuss("登录成功", user.getUserToken());
            }
        }

    }

    /**
     * Add user result data.
     *
     * @param user     the user
     * @param response the response
     * @return the result data
     */
    public ResultData addUser(Users user, HttpServletResponse response) {
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_phone", user.getUserPhone());
        QueryWrapper<Users> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("user_name", user.getUserName());
        List<Users> resname = mapper.selectList(queryWrapper1);
        List<Users> res = mapper.selectList(queryWrapper);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        user.setUserRegistrationTime(sdf.format(new Date()));
        if (redisUtils.get(user.getUserPhone()).equals(user.getCode())) {
            if (res.isEmpty()) {
                if (resname.isEmpty()) {
                    String md5Paw = DigestUtils.md5DigestAsHex(user.getUserPassword().getBytes());
                    user.setUserPassword(md5Paw);
                    if (user.getUserProfilePhoto() == null) {
                        user.setUserProfilePhoto("https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png");
                    }
                    int res1 = mapper.insert(user);
                    if (res1 > 0) {
                        Cookie cookie = new Cookie("message", "似乎刚注册的萌新，欢迎来到Preserved博客！！");
                        response.addCookie(cookie);
                        return ResultUtils.sucuss("注册成功,请登录！", res1);
                    } else {
                        return ResultUtils.sucuss("注册失败！", res1);
                    }
                } else {
                    throw new BisException("昵称已存在，请重新设置");
                }
            } else {
                throw new BisException("手机号已存在,请登录");
            }
        } else if (redisUtils.get(user.getUserPhone()) == null) {
            return ResultUtils.error("验证码过期，请重试！", null);
        } else {
            return ResultUtils.error("验证码错误，请重试！", null);
        }
    }

    /**
     * Up data user result data.
     *
     * @param users the users
     * @return the result data
     */
    public ResultData UpDataUser(Users users) {
        if (!String.valueOf(users.getUserId()).equals("null")) {
            int result = mapper.updateById(users);
            if (result > 0) {
                return ResultUtils.sucuss("信息更新完成！", result);
            } else {
                return ResultUtils.error("更新未完成，联系管理员！", result);
            }
        } else {
            return ResultUtils.error("用户信息为空", null);
        }
    }

    /**
     * Up data phone result data.
     *
     * @param users the users
     * @return the result data
     */
    public ResultData UpDataPhone(Users users) {
        if (users.getCode().equals(redisUtils.get(users.getUserPhone()))) {
            if (!String.valueOf(users.getUserPhone()).equals("null")) {
                UpdateWrapper<Users> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("user_phone",users.getUserPhone());
                updateWrapper.set("user_phone", users.getNewUserPhone());
                int result = mapper.update(null, updateWrapper);
                if (result > 0) {
                    return ResultUtils.sucuss("手机号绑定完成,请登录！", result);
                } else {
                    return ResultUtils.error("手机号未注册！！", result);
                }
            } else {
                return ResultUtils.error("用户信息为空", null);
            }
        } else {
            throw new BisException("验证码错误！");
        }
    }

    /**
     * Verification result data.
     *
     * @param parameter the parameter
     * @return the result data
     */
    public ResultData verification(SMSParameter parameter) {
        try {
            //短信模板中的参数列表
            String[] params = {VerifyCode.createRandom(true, 5), "5"};
            SmsSingleSender sender = new SmsSingleSender(parameter.getAppId(), parameter.getAppKey());
            SmsSingleSenderResult result = sender.sendWithParam("86", parameter.getUserPhone(),
                    parameter.getTemplateId(), params, parameter.getSmsSign(), "", "");
            if (result.errMsg.equals("OK")) {
                redisUtils.set(parameter.getUserPhone(), params[0], 300);
                return ResultUtils.sucuss("发送成功", null);
            }
        } catch (HTTPException | IOException | JSONException e) {
            // HTTP 响应码错误
            e.printStackTrace();
            return ResultUtils.error("发送失败", null);
        } // JSON 解析错误
        // 网络 IO 错误
        return ResultUtils.error("发送失败", null);
    }

    /**
     * Retrieve paw result data.
     *
     * @param users the users
     * @return the result data
     */
    public ResultData RetrievePaw(Users users) {
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_phone", users.getUserPhone());
        List<Users> list = mapper.selectList(queryWrapper);
        if (!list.isEmpty()) {
            if (redisUtils.get(users.getUserPhone()).equals(users.getCode())) {
                String md5Paw = DigestUtils.md5DigestAsHex(users.getUserPassword().getBytes());
                UpdateWrapper<Users> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("user_phone", users.getUserPhone());
                updateWrapper.set("user_password", md5Paw);
                int result = mapper.update(null, updateWrapper);
                if (result > 0) {
                    return ResultUtils.sucuss("修改成功！请重新登录。", result);
                } else {
                    throw new BisException("修改失败！");
                }
            } else {
                throw new BisException("验证码不一致，请重试！");
            }
        } else {
            throw new BisException("此号码还未注册，请先注册！");
        }
    }


    /**
     * User authentication result data.
     *
     * @param user the user
     * @return the result data
     */
    public ResultData UserAuthentication(Users user) {

        try {
            if (user.getUserToken() == null) {
                return ResultUtils.error("还未登陆，请登录!", null);
            } else {
                DecodedJWT jwt = JwtUtils.verify(user.getUserToken());
                String userPhone = jwt.getClaim("userPhone").asString();
                QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("user_phone", userPhone);
                Users res = mapper.selectOne(queryWrapper);
                if (res.getUserJurisdiction().equals("1")) {
                    res.setUserJurisdiction("管理员");
                } else {
                    res.setUserJurisdiction("用户");
                }
                return ResultUtils.sucuss("用户验证成功", res);
            }
        } catch (Exception e) {
            throw new BisException("登录过期，请重新登录！");
        }
    }

    /**
     * User img result data.
     *
     * @param users the users
     * @param file  the file
     * @return the result data
     */
    public ResultData UserImg(Users users, MultipartFile file) {
        if (users.getUserPhone() != null) {
            //判断文件不为空
            if (!file.isEmpty()) {
                //获取文件名
                String fileName = file.getOriginalFilename();
                //获取文件后缀
                String suffixName = fileName.substring(fileName.indexOf("."));
                //重新生成文件名
                String md5Name = DigestUtils.md5DigestAsHex(fileName.getBytes());
                String filename = md5Name + suffixName;
                //指定本地存入路径
                String filePath = "/www/admin/www.xinggaoya.com_80/wwwroot/blog/portrait/";
                String LinuxPath = filePath + filename;
                try {
                    file.transferTo(new File(LinuxPath));
                    Runtime.getRuntime().exec("chmod 777 -R " + LinuxPath);
                    String MysqlName = "http://www.xinggaoya.com/blog/portrait/" + filename;
                    users.setUserProfilePhoto(MysqlName);
                    UpdateWrapper<Users> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.eq("user_phone", users.getUserPhone()).set("user_profile_photo", users.getUserProfilePhoto());
                    int result = mapper.update(null, updateWrapper);
                    if (result > 0) {
                        return ResultUtils.sucuss("上传成功", result);
                    } else {
                        throw new BisException("上传失败！");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    return ResultUtils.error("文件上传失败", null);
                }
            } else {
                throw new BisException("文件是空的！");

            }
        } else {
            throw new BisException("用户信息为空，请登录！");
        }
    }

}
